package com.ironman.common.util;

import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;

/**
 * description 风速仪校验和
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2024/3/26 15:04
 */
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class ChecksumUtil {

    @Deprecated
    public static boolean windCheckout(String message) {
        int etxIndex = message.indexOf((char) 3);
        if (etxIndex == -1) {
            return false;
        }
        Integer checksum = windChecksum(message);
        return Integer.parseInt(message.substring(etxIndex + 1), 16) == checksum;
    }

    @Deprecated
    public static Integer windChecksum(String message) {
        int stxIndex = message.indexOf((char) 2);
        int etxIndex = message.indexOf((char) 3);
        if (stxIndex == -1 || etxIndex == -1 || etxIndex <= stxIndex) {
            return 256;
        }
        int checksum = 0;
        for (int i = stxIndex + 1; i < etxIndex; i++) {
            checksum ^= message.charAt(i);
        }
        return checksum;
    }

    public static boolean checkout(String message) {
        int end = message.indexOf('*');
        Integer checksum = checksum(message);
        return Integer.parseInt(message.substring(end + 1), 16) == checksum;
    }

    public static Integer checksum(String message) {
        int start = message.indexOf('$');
        int end = message.indexOf('*');
        int checksum = 0;
        for (int i = start + 1; i < end; i++) {
            checksum ^= message.charAt(i);
        }
        return checksum;
    }

    public static void main(String[] args) {
        String message = "\u0002S01,082,000.10,266,,,2024-03-26T05:15:44.4,+12.2,0002,\u000313";
        System.out.println(message);
        System.out.println(windCheckout(message));

        message = "$GNRMC,084901.403,A,3118.10601,N,12129.84417,E,0.735,333.37,190821,,,A*4C";
        System.out.println(checkout(message));

        message = "$WIMWV,200,T,001.16,M,A*0C";
        System.out.println(checkout(message));

        message = "$GPGGA,065040.000,3158.0951,N,12055.4075,E,1,05,2.0,24.1,M,7.1,M,,0000*5A";
        System.out.println(checkout(message));
    }
}
